#!/bin/bash

############################################################
# BEGIN EDIT SECTION

APACHE_FOLDER="$TWMFOLDER/apache"
DEFAULT_PORT='8080'
APACHE_CONFIG_NAME='httpd.conf'

# END EDIT SECTION
############################################################

apache_user=$1
apache_group=$2
dname=$3

whereis='whereis'
gawk='gawk'
grep='grep'

############################################################
# Unix system utils.
############################################################
echo -n "Looking for installed packages   .......... "
res=''
function get_tool()
{
        res=''
	util=$1

        for item in `$whereis -b $1`; do
                if [ `echo "$item" | $grep -Ec ".+/$1$"` == "1" ]; then
                        res=$item
                        break
                fi
        done;

        function print_err() {
                echo ""
                echo -e '\E[31m'"\033[1mError: \033[0m \033[1m$util\033[0m util has not been found.";
                echo "Installation aborted."
                echo -e "Please install \033[1m$util\033[0m and run TrafficPanel installation again."
                exit 1
        }

        if [ ! -n "$res" ]; then
                print_err
        elif [ -n "$res" ] && [ ! -x "$res" ]; then
                print_err
        fi
}

get_tool 'ifconfig'; ifconfig=$res
get_tool 'head'; head=$res
get_tool 'netstat'; netstat=$res
get_tool 'ls'; ls=$res
get_tool 'cat'; cat=$res
get_tool 'seq'; seq=$res
get_tool 'wc'; wc=$res
get_tool 'sed'; sed=$res
get_tool 'useradd'; useradd=$res
get_tool 'groupadd'; groupadd=$res
get_tool 'tar'; tar=$res
get_tool 'make'; make=$res
get_tool 'rm'; rm=$res
get_tool 'cp'; cp=$res
get_tool 'mkdir'; mkdir=$res
get_tool 'chown'; chown=$res
get_tool 'chmod'; chmod=$res
echo -e "[\E[32mok\033[0m]"

if [ `$cat /etc/group|$grep -c $apache_group` -eq '0' ]; then
        echo -n "Adding group for TrafficPanel apache   .......... "
        $groupadd $apache_group
		echo -e "[\E[32mok\033[0m]"
else
		echo -e "Group for TrafficPanel apache already exists.\n"
fi

if [ `$cat /etc/passwd|$grep -c $apache_user` -eq '0' ]; then
        echo -n "Adding user for TrafficPanel apache   .......... "
        $useradd $apache_user -c 'apache TrafficPanel user' -d $APACHE_FOLDER/apacherun -g $apache_group -s /bin/false
		echo -e "[\E[32mok\033[0m]"
else
        echo -e "User for TrafficPanel apache already exists."
fi

cd ./src/apache/
apache_src=`$ls|$grep -E '^apache.+\.tar\.gz$'`
apache_src_dir=`echo $apache_src|$sed 's/\(.*\)\.tar\.gz$/\1/'`
$tar -xzf $apache_src
cd ./$apache_src_dir/src

./Configure -file Configuration.twm
$make

echo ""
echo -n "Modification apache startup script                .......... "
function changeStartupscript()
{
         declare -a contents
         num=`$cat $1|$wc -l`
         for ((i=1; i<=$num; i++));
         do
                 contents[$i-1]=`$sed -n "${i}p; ${i}q" $1`
         done

         if [ -e "$1" ]; then
                 $rm "$1"
         fi

         for element in $($seq 0 $((${#contents[@]} - 1)))
         do
                 echo "${contents[$element]}"|$gawk -v pattern="$2" -v replto="$3" '{gsub (pattern, replto); print}' >> "$1"
         done
}

changeStartupscript './support/apachectl' 'PIDFILE=PIDFILE' "PIDFILE=$TWMFOLDER/apache/logs/httpd.pid"
changeStartupscript './support/apachectl' 'HTTPD=HTTPD' "HTTPD='$TWMFOLDER/apache/bin/httpd -f $TWMFOLDER/apache/conf/httpd.conf'"

$chmod +x ./support/apachectl

echo -e "[\E[32mok\033[0m]"


if [ ! -d "$TWMFOLDER/apache" ]; then
    mkdir "$TWMFOLDER/apache"
fi

while read dirname ; do
	$mkdir "$TWMFOLDER/apache/$dirname"
done <<!
    apacherun
    bin
    conf
    icons
    include
    libexec
    logs
    man
    proxy
!

$cp ./httpd "$TWMFOLDER/apache/bin"
$cp ./support/apachectl "$TWMFOLDER/apache/bin"
cd ../
$cp ./conf/access.conf-dist "$TWMFOLDER/apache/conf/access.conf"
$cp ./conf/magic "$TWMFOLDER/apache/conf"
$cp ./conf/mime.types "$TWMFOLDER/apache/conf"
$cp ./conf/srm.conf-dist "$TWMFOLDER/apache/conf/srm.conf"

cd ../../../
echo ""

#ip_choice () {
#       echo "Please enter valid 'ip address' for TrafficPanel apache:"
#       read IP
#       if [ ! $IP ]; then
#               ip_choice
#       fi
#}

port_choice () {
        echo -n "Please enter another port number: "
        read DEFAULT_PORT
        if [ ! $DEFAULT_PORT ]; then
                port_choice
        fi
}

port_check () {
        PortInUse=`$netstat -an|$grep -E '^tcp.+LISTEN'|$grep -c ":$DEFAULT_PORT "`
        if [ $PortInUse != '0' ]; then
                echo "Port $DEFAULT_PORT is already in use."
                port_choice
                port_check
        fi
}

ServerName=$dname
ServerAdmin="admin@$ServerName"

IP=`$ifconfig|$head -2|$grep 'inet addr'|$gawk '{print $2}'|$gawk -F: '{print $2}'`
#echo -e "Please enter TrafficPanel apache 'ip address' (press 'Enter' if you want use default value \"$IP\", otherwise press any character key and 'Enter')"
#read ans
#if [ $ans ];then
#       ip_choice
#       echo -e "You have selected \"$IP\" as 'ip address'.\n"
#else
#       echo -e "Using default 'ip address', i.e \"$IP\".\n"
#fi

echo -n "TrafficPanel apache port number [$DEFAULT_PORT] : "
read ans
if [ $ans ]; then
        DEFAULT_PORT=$ans
fi
port_check

echo ""
echo -n "Changing apache config file      .......... "
function editHttpdConfTempl ()
{
        declare -a contents

        num=`$cat ./apache_templates/$1|$wc -l`
        for ((i=1; i<=$num; i++));
        do
                contents[$i-1]=`$sed -n "${i}p; ${i}q" ./apache_templates/$1`
        done

        if [ -e "./apache_templates/$APACHE_CONFIG_NAME" ]; then
                $rm "./apache_templates/$APACHE_CONFIG_NAME"
        fi

        for element in $($seq 0 $((${#contents[@]} - 1)))
        do
                echo "${contents[$element]}"|$gawk -v pattern="$2" -v replto="$3" '{gsub (pattern, replto); print}' >> "./apache_templates/$APACHE_CONFIG_NAME"
        done
}
editHttpdConfTempl 'httpd.conf.TEMPLATE' 'TWMFOLDER' $TWMFOLDER
editHttpdConfTempl 'httpd.conf' 'SERVER_ADMIN' $ServerAdmin
editHttpdConfTempl 'httpd.conf' 'IP' $IP
editHttpdConfTempl 'httpd.conf' 'PORT' $DEFAULT_PORT
editHttpdConfTempl 'httpd.conf' 'APACHE_USER' $apache_user
editHttpdConfTempl 'httpd.conf' 'APACHE_GROUP' $apache_group
echo -e "[\E[32mok\033[0m]"

$cp -f ./apache_templates/httpd.conf "$APACHE_FOLDER/conf/"
if [ ! -d "$APACHE_FOLDER/apacherun" ]; then
        $mkdir "$APACHE_FOLDER/apacherun"
fi
$chown $apache_user:root "$APACHE_FOLDER/apacherun"

if [ -d "$TWMFOLDER/apache/cgi-bin" ]; then
	$rm -fR "$TWMFOLDER/apache/cgi-bin"
fi
if [ -d "$TWMFOLDER/apache/htdocs" ]; then
	$rm -fR "$TWMFOLDER/apache/htdocs"
fi

if [ $DEFAULT_PORT = '80' ]; then
        TWMlink="http://$ServerName/"
else
        TWMlink="http://$ServerName:$DEFAULT_PORT/"
fi

if [ -e '/tmp/twm.installation' ];then
	$rm -Rf /tmp/twm.installation
fi
echo "link:$TWMlink" >> /tmp/twm.installation
echo "ip:$IP" >> /tmp/twm.installation
echo "port:$DEFAULT_PORT" >> /tmp/twm.installation
echo "twm_apache:1" >> /tmp/twm.installation

perl ./saveWeb2ConfigFile.pl httpd_port="$DEFAULT_PORT"

echo -e "TrafficPanel apache is ready.\n"

exit 0
